package com.demo.zhihu.service;

import javax.inject.Singleton;

import com.demo.zhihu.data.QuestionDao;
import com.demo.zhihu.data.UserDao;
import com.demo.zhihu.model.Answer;
import com.demo.zhihu.model.User;
import com.demo.zhihu.model.UserProfile;

import cn.techarts.dragonfly.app.AbstractService;
import cn.techarts.dragonfly.app.helper.Cryptor;
import cn.techarts.dragonfly.data.trans.Transactional;

@Singleton
public class UserServiceImpl extends AbstractService implements UserService {

    @Override
    @Transactional
    public User login(String mobile, String password) {
        var dao = getMapper(UserDao.class);
        var user = dao.getUserByMobile(mobile);
        if(user == null) return null;
        var pwd =Cryptor.md5(password);
        var result = pwd.equals(user.getPassword());
//        user.setPassword(null); //Reset
        return result ? user : null;
    }

    @Override
    @Transactional
    public User register(String name, String mobile, String password) {
        var dao = getMapper(UserDao.class);
        if(dao.isMobileDuplicated(mobile) == 1) {
            return null;
        }

        var pwd = Cryptor.md5(password);
        var param = new User(name, mobile, pwd);
        dao.register(param);
        return param;
    }

        public User getMyProfile(int id, int page) {
            var userDao = getMapper(UserDao.class);
            var result = userDao.getUserProfile(id);
            if(result == null) return result;
            var questionDao = getMapper(QuestionDao.class);
            var param = new UserProfile(id, page);
            var questions = questionDao.getMyQuestions(param);
            var answers = questionDao.getMyAnswers(param);
            System.out.println(questions);
            System.out.println(answers);
            
            result.setMyQuestions(questions);
            result.setMyAnswers(answers);
            return result;
        }



}